package com.fliad.ai.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fliad.ai.dto.AiMcpDto;
import com.fliad.ai.entity.AiMcp;
import com.fliad.ai.service.AiMcpService;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Result;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.*;

/**
 * MCP 服务控制器
 */
@Slf4j
public class AiMcpController {

    @Inject
    private AiMcpService aiMcpService;

    // 创建 MCP 服务
    @Post
    @Mapping("")
    public Result<Boolean> create(@Body AiMcp mcp) throws SQLException {
        mcp.setId(IdUtil.getSnowflakeNextId());
        return Result.succeed(aiMcpService.createMcp(mcp));
    }

    // 查询单个 MCP 服务
    @Get
    @Mapping("/{id}")
    public Result<AiMcpDto> get(@Path("id") BigInteger id) throws SQLException {
        return Result.succeed(aiMcpService.getMcpById(id));
    }

    // 查询 MCP 服务列表
    @Get
    @Mapping("")
    public Result<List<AiMcpDto>> list() throws SQLException {
        return Result.succeed(aiMcpService.getMcpList());
    }

    // 更新 MCP 服务
    @Put
    @Mapping("/{id}")
    public Result<Boolean> update(@Path("id") Long id, @Body AiMcp mcp) throws SQLException {
        return Result.succeed(aiMcpService.updateMcp(id, mcp));
    }

    // 删除 MCP 服务
    @Delete
    @Mapping("/{id}")
    public Result<Boolean> delete(@Path("id") BigInteger id) throws SQLException {
        return Result.succeed(aiMcpService.deleteMcp(id));
    }

    // 实现/ai/mcp/tool接口
    @Post
    @Mapping("tool")
    public Result<ONode> tool(@Body Map<String, Object> params) {
        String mcpName = (String) params.get("mcpName");
        String toolName = (String) params.get("toolName");
        Map<String, Object> inputParams = (Map<String, Object>) params.get("args");

        String result = aiMcpService.callMcpTool(mcpName, toolName, inputParams);
        return Result.succeed(StrUtil.isBlankIfStr(result) ? null : ONode.loadStr(result));
    }

    // 查询单个 MCP 服务（从mcp_square.json读取）
    @Get
    @Mapping("/square/{id}")
    public Result<AiMcp> getSquareMcp(@Path("id") String id) throws Exception {
        return Result.succeed(aiMcpService.getSquareMcp(id));
    }

    // 查询 MCP 服务列表（从mcp_square.json读取）
    @Get
    @Mapping("/square")
    public Result<List<AiMcpDto>> listSquareMcp() throws Exception {
        return Result.succeed(aiMcpService.listSquareMcp());
    }

    //  MCP 服务到 ai_mcp 表
    @Post
    @Mapping("/install")
    public Result<Boolean> install(@Body Map<String, Object> params) throws SQLException {
        return Result.succeed(aiMcpService.install(params));
    }

}
